package com.iot.ammeter.exception;

import com.iot.ammeter.constant.Constant;
import com.iot.ammeter.responseResult.ResponseResult;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * @ClassName: GlobalExceptionHandler
 * @Author: Basil
 * @Date: 2021/9/26 下午2:19
 * @Version: 1.0
 * @Description: 全局异常处理
 **/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 业务异常
     *
     * @param e 异常
     */
    @ExceptionHandler(value = BusinessExceptions.class)
    public ResponseResult handler(BusinessExceptions e) {
        return ResponseResult.FAILED(e.getCode(), e.getMessage());
    }


    /**
     * 运行时异常抛出，如 10/0 会抛出该异常
     *
     * @param e 异常
     * @return ResponseResult
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = RuntimeException.class)
    public ResponseResult handler(RuntimeException e) {
        log.error("运行时异常-------->{}", e.getMessage());
        return ResponseResult.FAILED(Constant.Exception.ERROR, e.getMessage());
    }

    /**
     * 实体校验异常
     *
     * @param e 异常
     * @return ResponseResult
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseResult handler(MethodArgumentNotValidException e) {
        log.error("实体校验异常-------->{}", e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        ObjectError objectError = bindingResult.getAllErrors().stream().findFirst().get();
        return ResponseResult.FAILED(Constant.Exception.ERROR, objectError.getDefaultMessage());
    }

    /**
     * 处理权限不足异常
     *
     * @param e 异常
     * @return ResponseResult
     */
    @ResponseStatus(HttpStatus.FORBIDDEN)
    @ExceptionHandler(value = AccessDeniedException.class)
    public ResponseResult accessDeniedExceptionHandler(AccessDeniedException e) {
        log.error("不允许访问！原因是:-------->{}", e.getMessage());
        return ResponseResult.FAILED("403", e.getMessage());
    }

    /**
     * 处理令牌过期异常
     *
     * @param e 异常
     * @return ResponseResult
     */
    @ExceptionHandler(value = ExpiredJwtException.class)
    public ResponseResult expiredJwtExceptionHandler(ExpiredJwtException e) {
        log.info("用户身份认证过期-------->{}", e.getMessage());
        return ResponseResult.FAILED("401", "用户身份认证过期");
    }
}
